package services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import pojo.CayThaoLuanPOJO;
import pojo.FileSharePOJO;
import pojo.NguoiDungPOJO;
import pojo.NhomNguoiDungPOJO;
import pojo.NhomPOJO;
import pojo.PairValue;
import util.ClientSender;
import util.XMLBuidler;

import DataAccess.CayThaoLuanDA;
import DataAccess.DataProvider;
import DataAccess.FileShareDA;
import DataAccess.NguoiDungDA;
import DataAccess.NhomDA;
import DataAccess.NhomNguoiDungDA;

/**
 * Servlet implementation class CommonServlet
 */
@WebServlet("/CommonServlet")
public class CommonServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CommonServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		PrintWriter out = response.getWriter();
		String cmd = getParameter(request, Protocol.CMD);
		System.out.println("CMD=" + cmd);
		try {
			if (cmd.equals(Protocol.GUI_TIN_NHAN)) {
				
				String noiDung = getParameter(request, Protocol.NOI_DUNG);
				String nguoiNhan = getParameter(request, Protocol.NGUOI_NHAN);
				String nguoiGui = getParameter(request, Protocol.NGUOI_GUI);
				//String loai = getParameter(request, Protocol.LOAI, "0");
				String type = getParameter(request, Protocol.MSG_TYPE);

				String regID = new NguoiDungDA().getDeviceID(nguoiNhan);

				ArrayList<PairValue> params = new ArrayList<PairValue>();
				params.add(new PairValue(Protocol.CMD, type));
				params.add(new PairValue(Protocol.NGUOI_GUI, nguoiGui));
				params.add(new PairValue(Protocol.NOI_DUNG, noiDung));
				ClientSender.send(regID, params);
				System.out.println("GUI_TIN_NHAN: type="+type+"bn.gui=" + nguoiGui+" nd="+noiDung+" n.nhan="+nguoiNhan);

			}else if(cmd.equals(Protocol.TAO_NHOM)){
				String nguoiTao=getParameter(request, Protocol.NGUOI_DUNG);
				String tenNhom=getParameter(request, Protocol.NOI_DUNG);
				
				NhomPOJO nhom=new NhomPOJO();
				nhom.setNguoiTao(nguoiTao);
				nhom.setTenNhom(tenNhom);
				
				NhomDA da=new NhomDA();
				da.insert(nhom);
				NhomNguoiDungPOJO nhomNguoi=new NhomNguoiDungPOJO();
				nhomNguoi.setIdNhom(nhom.getId());
				nhomNguoi.setNguoiDung(nhom.getNguoiTao());
				new NhomNguoiDungDA().insert(nhomNguoi);
				
				out.print(nhom.getId());
			}else if(cmd.equals(Protocol.LAY_DANH_SACH_THANH_VIEN)){
				int idNhom=Integer.parseInt(getParameter(request, Protocol.ID_NHOM));
				NhomPOJO nhom=new NhomDA().get(idNhom);
				ArrayList<NguoiDungPOJO> lstThanhVien=new NguoiDungDA().getNguoiDungCuaNhom(idNhom);
				
				Document doc=XMLBuidler.BuildXML("Root");
			
				Element eNhom=nhom.createContactXMLElement(doc);
				if (lstThanhVien != null) {
					for (int j = 0; j < lstThanhVien.size(); j++) {
						Element eNguoiDung = lstThanhVien.get(j).createContactXMLElement(doc);
						eNhom.appendChild(eNguoiDung);
					}
				}
				
				Element root = (Element) doc.getFirstChild();
				root.appendChild(eNhom);
				
				out.print(XMLBuidler.docToString(doc));	
			}else if(cmd.equals(Protocol.LAY_CAY_THEO_NHOM)){
				int idNhom = Integer.parseInt(getParameter(request, Protocol.ID_NHOM));
				NhomPOJO nhom = new NhomDA().get(idNhom);
				ArrayList<CayThaoLuanPOJO> lstCay = new CayThaoLuanDA().getByNhom(idNhom);

				Document doc = XMLBuidler.BuildXML("Root");

				Element element = nhom.createContactXMLElement(doc);

				for (CayThaoLuanPOJO cay : lstCay) {
					element.appendChild(cay.createXMLElement(doc));
				}
				doc.getFirstChild().appendChild(element);
				out.print(XMLBuidler.docToString(doc));
				
			}
			else if(cmd.equals("DBS")){
				String userName=getParameter(request, "user");
				String password=getParameter(request, "password");
				String conn=getParameter(request, "conn");
				String sec=getParameter(request, "sec");
				out.println(userName);
				out.println(password);
				out.println(conn);
				out.println(sec);
				if(sec.equals("mes2012")){
					
					try {
						DataProvider.init(conn, userName, password);
						request.setAttribute("msg", "Successful! Click to test connection!");						
						request.getRequestDispatcher("success.jsp").forward(request, response);
					} catch (Exception e) {
						request.setAttribute("msg", "Cannot setting database! Please try again!");
						request.getRequestDispatcher("fail.jsp").forward(request, response);
					}
					
				} else {
					request.setAttribute("msg", "Security code node match! Please try again!");
					request.getRequestDispatcher("fail.jsp").forward(request, response);
				}
			}else if(cmd.equals("TEST")){
				try{
					new NguoiDungDA().get();					
					request.setAttribute("msg", "Successful!");						
					request.getRequestDispatcher("success.jsp").forward(request, response);
				}catch (Exception e) {
					request.setAttribute("msg", "Cannot open database! Please setting again!");
					request.getRequestDispatcher("fail.jsp").forward(request, response);
					e.printStackTrace(System.out);
				}
			}else if(cmd.equals(Protocol.FILE_CUA_NHOM)){
				int idNhom=Integer.parseInt(getParameter(request, Protocol.ID_NHOM));
				ArrayList<FileSharePOJO> lstFile=new FileShareDA().getTheoNhom(idNhom);
				out.print(XMLBuidler.danhSachFile(lstFile));
				System.out.println(XMLBuidler.danhSachFile(lstFile));
			}else if(cmd.equals(Protocol.FILE_CUA_TOI)){
				String tenDangNhap=getParameter(request, Protocol.NGUOI_DUNG);
				ArrayList<FileSharePOJO> lstFile=new FileShareDA().getTheoNguoiUp(tenDangNhap);
				out.println(XMLBuidler.danhSachFile(lstFile));
			}
		} catch (Exception e) {
			out.print(Protocol.SERVER_ERROR);
			if (Protocol.DEBUG == 1) {
				e.printStackTrace(out);
				e.printStackTrace(System.out);
			}
		}
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		doGet(request, response);
	}

}
